package service

import (
	"douyin/models"
	"douyin/repository/mysql"
	"douyin/utils/pkg/jwt"
	"douyin/utils/pkg/snowflake"
)

// Register 用户注册具体逻辑
func Register(p *models.UserRequest) (userId int64, token string, err error) {
	// 1.判断用户存不存在
	if err := mysql.CheckUserExist(p.UserName); err != nil {
		return -1, "", err
	}
	// 2.生成UID
	userId = snowflake.GenID()
	// 构造一个User实例
	user := &models.User{
		Id:            userId,
		Name:          p.UserName,
		NickName:      p.UserName, //默认使用username作为nickname,若前端增加修改nickname的接口，修改此值就行
		Password:      p.Password,
		FollowCount:   0,
		FollowerCount: 0,
		IsFollow:      false,
	}
	// 3.生成Token
	token, err = jwt.GenToken(user.Id, user.Name)
	if err != nil {
		return
	}
	// 4.保存进数据库
	err = mysql.InsertUser(user)
	return userId, token, err
}

// Login 用户登录具体逻辑
func Login(p *models.UserRequest) (userId int64, token string, err error) {
	user := &models.User{
		Id:            0,
		Name:          p.UserName,
		Password:      p.Password,
		FollowCount:   0,
		FollowerCount: 0,
		IsFollow:      false,
	}
	//传递的是指针，就能在生成Token时拿到user.UserID
	if err = mysql.Login(user); err != nil {
		return
	}
	//生成token
	token, err = jwt.GenToken(user.Id, user.Name)
	if err != nil {
		return
	}
	return user.Id, token, err
}

// UserInfo 查询用户信息
func UserInfo(userId, otherId int64) (user models.User, err error) {
	return mysql.GetUserInfoByUserId(userId, otherId)
}
